<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.order_number"
        placeholder="订单号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="轨迹状态" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加轨迹
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="订单号" width="180">
        <template slot-scope="scope">
          <span class="link-type" @click="handleViewOrder(scope.row)">{{ scope.row.express_order ? scope.row.express_order.order_number : '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轨迹状态" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">{{ statusLabelMap[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="位置" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.location }}
        </template>
      </el-table-column>
      <el-table-column label="描述" width="300" align="center">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="操作人" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.operator }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="订单" prop="express_order_id">
          <el-select v-model="temp.express_order_id" filterable placeholder="请选择订单" style="width: 100%">
            <el-option
              v-for="item in orders"
              :key="item.id"
              :label="item.order_number"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="轨迹状态" prop="status">
          <el-select v-model="temp.status" placeholder="请选择轨迹状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="temp.location" placeholder="请输入位置信息" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="3" placeholder="请输入轨迹描述" />
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="temp.operator" placeholder="请输入操作人" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from '@/api'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
  name: 'TrackManage',
  components: { Pagination },
  directives: { waves },
  filters: {
    parseTime
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        order_number: undefined,
        status: undefined
      },
      orders: [],
      statusOptions: [
        { value: 'pending', label: '待处理' },
        { value: 'processing', label: '处理中' },
        { value: 'shipped', label: '已发货' },
        { value: 'in_transit', label: '运输中' },
        { value: 'out_for_delivery', label: '派送中' },
        { value: 'delivered', label: '已送达' },
        { value: 'cancelled', label: '已取消' }
      ],
      statusTypeMap: {
        pending: 'info',
        processing: 'primary',
        shipped: 'success',
        in_transit: 'warning',
        out_for_delivery: 'warning',
        delivered: 'success',
        cancelled: 'danger'
      },
      statusLabelMap: {
        pending: '待处理',
        processing: '处理中',
        shipped: '已发货',
        in_transit: '运输中',
        out_for_delivery: '派送中',
        delivered: '已送达',
        cancelled: '已取消'
      },
      temp: {
        id: undefined,
        express_order_id: undefined,
        status: '',
        location: '',
        description: '',
        operator: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑物流轨迹',
        create: '添加物流轨迹'
      },
      rules: {
        express_order_id: [{ required: true, message: '请选择订单', trigger: 'change' }],
        status: [{ required: true, message: '请选择轨迹状态', trigger: 'change' }],
        location: [{ required: true, message: '请输入位置信息', trigger: 'blur' }],
        description: [{ required: true, message: '请输入轨迹描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getOrders()
  },
  methods: {
    getList() {
      this.listLoading = true
      http.logisticsTrack.page(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getOrders() {
      http.expressOrder.simpleList().then(response => {
        this.orders = response.data.rows
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        express_order_id: undefined,
        status: '',
        location: '',
        description: '',
        operator: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          http.logisticsTrack.addTrack(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })

            // 更新订单状态
            const data = {
              id: this.temp.express_order_id,
              status: this.temp.status,
              remark: this.temp.description
            }

            http.expressOrder.updateStatus(data).then(() => {
              this.getList()
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      if (row.express_order) {
        this.temp.express_order_id = row.express_order.id
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          http.logisticsTrack.update(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该物流轨迹吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.logisticsTrack.delete(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleViewOrder(row) {
      if (row.express_order) {
        this.$router.push({ path: '/order/detail', query: { id: row.express_order.id }})
      }
    }
  }
}
</script>

<style scoped>
.link-type {
  color: #409EFF;
  cursor: pointer;
}
</style>
